package com.example.myAnnotation;

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author 郅占伟
 * @ClassName AnnotationTest
 * @Description TODO
 * @Date 2024年05月27日
 * @Version: 1.0
 */
public class AnnotationTest {
    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        // 新建Person对象
        Person person = new Person();

        // 获取Person的class实例
        Class<Person> personClass = Person.class;
        // 获取 somebody() 方法的Method实例
        Method somebody = personClass.getMethod("somebody", new Class[]{String.class, int.class});

        // 执行该方法
        somebody.invoke(person,new Object[]{"Tom", 25});
        iteratorAnnotation(somebody);


        // 获取 somebody 方法的Method实例
        Method empty = personClass.getMethod("empty", new Class[]{});
        // 执行该方法
        empty.invoke(person,new Object[]{});
        iteratorAnnotation(empty);
    }

    public static void iteratorAnnotation(Method method){
        // 判断 Somebody 方法是否包含注解
        if (method.isAnnotationPresent(MyAnnotation.class)){
            // 获取该方法的MyAnnotation注解实例
            MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
            // 打印注解的属性值
            String[] values = annotation.value();
            for (String value : values){
                System.out.print(value + ",");
            }
            System.out.println();
        }

        // 获取方法上的所有注解，并打印出来
        Annotation[] annotations = method.getAnnotations();
        for (Annotation annotation : annotations){
            System.out.println(annotation.toString());
        }
    }
}
